package com.jason.orc;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.jason.orc.enums.TencentOrcHandleTypeEnum;
import com.jason.orc.vo.TencentOrcVo;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

import static com.jason.orc.enums.TencentOrcHandleTypeEnum.GENERAL_OCR;

/**
 * 腾讯优图 ORC识别 客户端
 * @author JasonChoi
 */
public class TencentOrcClient {
    /**
     * 开发者创建应用时的QQ号
     */
    private String userQQ;
    /**
     * 开发者创建应用后的AppID
     */
    private String appID;
    /**
     * 开发者创建应用后的SecretID
     */
    private String secretID;
    /**
     * 开发者创建应用后的SecretKey
     */
    private String secretKey;


    public TencentOrcClient(String userQQ, String appID, String secretID, String secretKey) {
        this.userQQ = userQQ;
        this.appID = appID;
        this.secretID = secretID;
        this.secretKey = secretKey;
    }

    public TencentOrcVo orcByImagePath(String imagePath){
        String imgStr = Base64.encode(FileUtil.readBytes(imagePath));
        String params = new JSONObject().fluentPut("app_id", appID).fluentPut("image", imgStr).toJSONString();
        return orc(params, GENERAL_OCR);
    }

    public TencentOrcVo orcByImageUrl(String imageUrl){
        String params = new JSONObject().fluentPut("app_id", appID).fluentPut("url", imageUrl).toJSONString();
        return orc(params, GENERAL_OCR);
    }

    public TencentOrcVo orc(String params, TencentOrcHandleTypeEnum handleTypeEnum){
        String respStr = HttpUtil.createPost(handleTypeEnum.getOrcUrl()).header("Authorization", getSign()).body(params).execute().body();
        TencentOrcVo tencentOrcVo = JSONObject.parseObject(respStr, TencentOrcVo.class);
        return tencentOrcVo;
    }

    /**
     * Authorization方法
     * @return sign
     * @throws Exception
     */
    private String getSign(){
        long nowTime = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        long endTime = LocalDateTime.now().plusMinutes(5).toEpochSecond(ZoneOffset.of("+8"));
        String randomNum = RandomUtil.randomNumbers(10);
        String orignal = StrUtil.format("u={}&a={}&k={}&e={}&t={}&r={}&f=",
                userQQ, appID, secretID, endTime, nowTime, randomNum);
        byte[] hmacSign = SecureUtil.hmacSha1(secretKey).digest(orignal);
        byte[] all = new byte[hmacSign.length + orignal.getBytes().length];
        System.arraycopy(hmacSign, 0, all, 0, hmacSign.length);
        System.arraycopy(orignal.getBytes(), 0, all, hmacSign.length, orignal.getBytes().length);
        return Base64.encode(all);
    }

}
